<template>
  <div class="container">
    <n-h3 prefix="bar">咨询功能</n-h3>
    <div>
      <n-form-item label="状态">
        <n-switch :default-value="form.switch != null" v-model:value="form.switch">
          <template #checked>
            开启
          </template>

          <template #unchecked>
            关闭
          </template>
        </n-switch>
      </n-form-item>
      <n-collapse-transition :show="form.switch">
        <n-form-item label="单次咨询定价">
          <n-input-number v-model:value="form.coin" :min="0" :max="1000" placeholder="最低0金币" :show-button="false">
            <template #suffix>
              金币
            </template>
          </n-input-number>
        </n-form-item>
      </n-collapse-transition>
      <n-button type="primary" :loading="requesting" :disabled="requesting" @click="update">更新状态</n-button>
    </div>
  </div>
</template>

<script setup>

import {useUserStore} from "@/stores/user.js";
import {computed, ref} from "vue";
import {useRequests} from "@/common/requests.js";
import {useMessage, useNotification} from "naive-ui";

const userStore = useUserStore()
const requests = useRequests()
const message = useMessage()
const notify = useNotification()

const form = ref({
  switch: userStore?.profile?.consult_price != null,
  coin: userStore?.profile?.consult_price
})
const requesting = ref(false)
const update = () => {
  requesting.value = true
  let price = null
  if (form.value.switch === true) {
    price = parseInt(form.value.coin)
  }

  requests.profile.updateConsultPrice({price}).then(resp => {
    requesting.value = false
    if (resp.ret === 0) {
      requests.profile.getMe().then(resp => {
        if (resp.ret === 0) {
          userStore.$patch({profile: resp.data})
          form.value.switch = userStore?.profile?.consult_price != null
          form.value.coin = userStore?.profile?.consult_price
        }
      })

      message.success("更新成功")
    } else {
      message.error(resp?.data ?? resp?.msg ?? "未知错误")
    }
  }).catch(err => {
    requesting.value = false

    console.log(err)
    notify.error({content: "出错了", meta: err.toString(), duration: 1500})
  })
}
</script>
